package com.demo.controller;
import com.demo.service.SendSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin //跨域支持
@RequestMapping("ctCode")
public class SendController {

    @Autowired
    private SendSmsService sendSmsService;


    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("/send/{mobile}")
    public String code(@PathVariable("mobile")  String mobile){
        //调用发送接口,(模拟真实业务 redis)
        String code= redisTemplate.opsForValue().get(mobile);
        if (!StringUtils.isEmpty(code)){
            return  mobile+":"+code+"已存在,还没有过期";
        }
        //生成验证码并存储在redis中
        code = UUID.randomUUID().toString().substring(0, 4);
        HashMap<String,Object> param=new HashMap<>();
        param.put("code",code);
        boolean isSend=sendSmsService.send(mobile,"SMS_219605115",param);

        if (isSend){
            redisTemplate.opsForValue().set(mobile,code,5, TimeUnit.SECONDS);
            return  mobile+":"+code+" 发送成功!";
        }else{
            return  "发送失败";
        }
    }
}